import { de, ro } from "element-plus/es/locales.mjs";

// src/utils/storage.js
export const storage = {
  ignoreKeys: ["be-rememberMe"],
  // 设置
  set(key, value, expire = null) {
    const data = { value, expire: expire ? Date.now() + expire : null };
    localStorage.setItem(key, JSON.stringify(data));
  },

  // 获取
  get(key, defaultVal = null) {
    const raw = localStorage.getItem(key);
    if (!raw) return defaultVal;
    try { 
      const { value, expire } = JSON.parse(raw);
      if (expire && Date.now() > expire) {
        this.remove(key);
        return defaultVal;
      }
      return value;
    } catch {
      return defaultVal;
    }
  },

  addIgnoreKey(...keys) { 
    keys.flat().forEach(key => {
      if (!this.ignoreKeys.includes(key)) {
        this.ignoreKeys.push(key);
      }
    });
  },

  removeIgnoreKey(...keys) { 
    keys.flat().forEach(key => {
      let idx;
      while ((idx = this.ignoreKeys.indexOf(key)) !== -1) {
        this.ignoreKeys.splice(idx, 1);
      }
    });
  },

  // 删除
  remove(key) {
    if (this.ignoreKeys.includes(key)) {
      return; // 如果键名在忽略列表中，则不进行删除
    }
    localStorage.removeItem(key);
  },

  // 清空所有
  clear() {
    // 创建正则表达式，用于模糊匹配
    const regex = new RegExp("be-", "i"); // "i" 表示不区分大小写

    for (let key in localStorage) {
      if (regex.test(key)) {
        // 如果键名匹配关键字
        storage.remove(key); // 删除该键值对
      }
    }
  },
};
